﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.IO.Ports;

namespace SerialPortModel
{
    public delegate void DataReceived(object sender, SerialDataReceivedEventArgs e);
    public class CSerialPortModel
    {
        private SerialPort com;
        public CSerialPortModel(string portName, int baudRate, int dataBits, Parity parity, StopBits stopBits)
        {
            com = new SerialPort();
            com.BaudRate = baudRate;
            com.PortName = portName;
            com.DataBits = dataBits;
            com.StopBits = stopBits;
            com.Parity = parity;
        }

        public void SetDataReceived(DataReceived dataReceived)
        {
            com.DataReceived += new SerialDataReceivedEventHandler(dataReceived);
        }

        public void SendData(Byte[] TxData)
        {
            com.Write(TxData, 0, TxData.Length);
        }

        public bool Open()
        {
            try
            {
                if (com.IsOpen) com.Close();
                if (!com.IsOpen) com.Open();
                return true;
            }
            catch (Exception)
            {
            }
            return false;
        }
        public void Close()
        {
            if (com.IsOpen) com.Close();
        }
        public bool IsOpen()
        {
            return com.IsOpen;
        }
    }
}
